﻿
using System.Linq;

using SmallShop.Frame;
using SmalShop.Model;

namespace SmallShop.Bll
{
    /// <summary>
    /// 产品业务处理
    /// </summary>
    public class ProductBiz: BaseBiz<ProductModel>
    {
        public override ResultModel Add(ProductModel model)
        {
            string msg;
            if (!CheckModel(model, out msg))
            {
                return new ResultModel { Code = ResultModel.InValid, Message = msg};
            }
            var count = Query(it => it.Title == model.Title).Count();
            if(count > 0)
            {
                return new ResultModel { Code = ResultModel.Failure, Message = "已有该产品" };
            }
            return base.Add(model);
        }


        public override ResultModel Update(ProductModel model)
        {
            var msg ="无效的修改数据";
            if ( model.Id < 1|| !CheckModel(model, out msg))
            {
                return new ResultModel { Code = ResultModel.InValid, Message = msg };
            }
            var m = Query().SingleOrDefault(it => it.Id == model.Id);
            if (m == null)
            {
                return new ResultModel { Code = ResultModel.InValid, Message = msg };
            }
            var p = Query(it => it.Title == model.Title).FirstOrDefault();
            if (p != null && p.Id != model.Id )
            {
                return new ResultModel { Code = ResultModel.Failure, Message = "产品重名了" };
            }
            m.Title = model.Title;
            m.ImgUrl = model.ImgUrl;
            m.CateId = model.CateId;
            m.Status = model.Status;
            m.IsShowInHome = model.IsShowInHome;
            m.Weight = model.Weight;
            return base.Update(m);
        }

        public static bool CheckModel(ProductModel model, out string msg)
        {
            msg = null;
            if (model.Title.IsNullOrEmpty())
            {
                msg = "无效的产品名称";
                return false;
            }
            if (model.CateId < 1)
            {
                msg = "无效的产品类型";
                return false;
            }
            if (model.Unit.IsNullOrEmpty() )
            {
                msg = "无效的产品单位";
                return false;
            }
            if (model.Price < 0.01m)
            {
                msg = "无效的价格";
                return false;
            }
            return true;
        }
    }
}
